//
//  CYProjectViewController.m
//  cyydt
//
//  Created by chu on 2019/1/14.
//  Copyright © 2019 chu. All rights reserved.
//

#import "CYProjectViewController.h"
#import "CYCategrayModel.h"

#import "CYProjectBannerCollectionViewCell.h"
#import "CYProjectLabelCollectionViewCell.h"
#import "CYProjectCollectionViewCell.h"
#import "CYProjectHeaderCollectionReusableView.h"
#import "CYImageCollectionViewCell.h"

#import "CYBannerModel.h"
#import "CYProjectModel.h"

#import "CYProjectCateViewController.h"
#import "CYProjectDetailViewController.h"
#import "CYSearchViewController.h"

#import "CYAllCategaryViewController.h"
#import "CYWoShiChuangYeZheViewController.h"
#import "CYQiYeRuZhuViewController.h"

@interface CYProjectViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
{
    NSArray *_labelImages;
    NSArray *_labelTitles;
}

@property (nonatomic,strong) HW3DBannerView *banner;

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *dataSourceArr;

@property (nonatomic, strong) NSMutableArray *bannerArr;//轮播

@property (nonatomic, strong) NSMutableArray *cateArr;//分类

@property (nonatomic, strong) NSArray *data;//分类

@end

@implementation CYProjectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.title = @"找项目";
    _labelImages = @[@"zxm_meishi", @"zxm_jczs", @"zxm_fsfz", @"zxm_shfw", @"zxm_jnhb", @"jzyp", @"zxm_mrhf", @"zxm_jypx", @"zxm_qcyp", @"zxm_fdfl"];
    _labelTitles = @[@"餐饮美食", @"服装服饰", @"建材装饰", @"生活服务", @"节能环保", @"家居用品", @"美容护肤", @"教育培训", @"汽车用品", @"更多分类"];
    [self RightsetupNavgationItemWithpictureName:@"zxm_ss"];
    [self.view addSubview:self.collectionView];
    
    [self getBanner];
    [self getData];
    [self getCate];
}

- (void)RighttouchEvent{
    CYSearchViewController *search = [[CYSearchViewController alloc] init];
    [[AppDelegate sharedAppDelegate] pushViewController:search];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        CYProjectCateViewController *cate = [[CYProjectCateViewController alloc] init];
        cate.cateArr = self.data;
        switch (indexPath.item) {
            case 0:
                cate.param = @{@"type":@3, @"big_catid":@"1"};
                break;
            case 1:
                cate.param = @{@"type":@3, @"big_catid":@"9"};
                break;
            case 2:
                cate.param = @{@"type":@3, @"big_catid":@"13"};
                break;
            case 3:
                cate.param = @{@"type":@3, @"big_catid":@"245"};
                break;
            case 4:
                cate.param = @{@"type":@3, @"big_catid":@"15"};
                break;
            case 5:
                cate.param = @{@"type":@3, @"big_catid":@"7"};
                break;
            case 6:
                cate.param = @{@"type":@3, @"big_catid":@"5"};
                break;
            case 7:
                cate.param = @{@"type":@3, @"big_catid":@"10"};
                break;
            case 8:
                cate.param = @{@"type":@3, @"big_catid":@"6"};
                break;
            case 9:
                {
                    CYAllCategaryViewController *all = [[CYAllCategaryViewController alloc] init];
                    [[AppDelegate sharedAppDelegate] pushViewController:all];
                    return;
                }
                break;
            default:
                break;
        }
        
        cate.title = _labelTitles[indexPath.item];
        [[AppDelegate sharedAppDelegate] pushViewController:cate];
    }
    
    if (indexPath.section == 3) {
        CYProjectDetailViewController *detail = [[CYProjectDetailViewController alloc] init];
        detail.model = self.dataSourceArr[indexPath.row];
        [[AppDelegate sharedAppDelegate] pushViewController:detail];
    }
    if (indexPath.section == 2) {
        if (indexPath.item == 0) {
            CYWoShiChuangYeZheViewController *chuangye = [[CYWoShiChuangYeZheViewController alloc] init];
            [[AppDelegate sharedAppDelegate] pushViewController:chuangye];
        }else{
            CYQiYeRuZhuViewController *chuangye = [[CYQiYeRuZhuViewController alloc] init];
            [[AppDelegate sharedAppDelegate] pushViewController:chuangye];
        }
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 4;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return self.cateArr.count >= 10 ? 10 : self.cateArr.count;
    }else if (section == 2){
        return 2;
    }
    return self.dataSourceArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        CYProjectBannerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CYProjectBannerCollectionViewCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[CYProjectBannerCollectionViewCell alloc] init];
        }
        [cell.backView addSubview:self.banner];
        NSMutableArray *logos = [NSMutableArray arrayWithCapacity:0];
        for (CYBannerModel *model in self.bannerArr) {
            [logos addObject:model.logo_item_sg];
        }
        self.banner.data = logos;
        return cell;
    }else if (indexPath.section == 1){
        CYProjectLabelCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CYProjectLabelCollectionViewCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[CYProjectLabelCollectionViewCell alloc] init];
        }
        cell.headImageView.image = [UIImage imageNamed:_labelImages[indexPath.item]];
        cell.titleLabel.text = _labelTitles[indexPath.item];
        return cell;
    }else if (indexPath.section == 2){
        CYImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CYImageCollectionViewCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[CYImageCollectionViewCell alloc] init];
        }
        
        if (indexPath.item == 0) {
            cell.headImageView.image = [UIImage imageNamed:@"zxm_cyz"];
            cell.titleLabel.text = @"我是创业者";
            cell.introLabel.text = @"已有 224189 位创业者登记意向";
        }else{
            cell.headImageView.image = [UIImage imageNamed:@"zxm_pps"];
            cell.titleLabel.text = @"我是品牌商";
            cell.introLabel.text = @"已有 2000,000+家企业通过资质审核";
        }
        
        return cell;
    }else{
        CYProjectCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CYProjectCollectionViewCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[CYProjectCollectionViewCell alloc] init];
        }
        cell.model = self.dataSourceArr[indexPath.item];
        return cell;
    }
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return CGSizeMake(kWindowW, 130);
    }else if (indexPath.section == 1){
        return CGSizeMake(kWindowW / 5, 85);
    }else if (indexPath.section == 2){
        return CGSizeMake(kWindowW / 2, 100);
    }else{
        CYProjectModel *model = self.dataSourceArr[indexPath.item];
        UIView *view = [[Tool sharedInstance] setSignView:model.mode andBackgroundColor:RGBOF(0xF5F7FB) andTitleColor:RGBOF(0x97A2B9) Height:20 andFont:[UIFont systemFontOfSize:12] andMargin_x:8 andMargin_y:8 andMaxWidth:kWindowW - 150];
        return CGSizeMake(kWindowW, 115 + view.frame.size.height);
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 3) {
        return CGSizeMake(kWindowW, 45);
    }
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    
    return CGSizeZero;
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (section == 2) {
        return UIEdgeInsetsMake(10, 0, 0, 0);
    }else if (section == 3){
        return UIEdgeInsetsMake(10, 0, 10, 0);
    }
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *view = nil;
    if (indexPath.section == 3) {
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CYProjectHeaderCollectionReusableView" forIndexPath:indexPath];
            CYProjectHeaderCollectionReusableView *footer = (CYProjectHeaderCollectionReusableView *)view;
            
            return footer;
        }
    }
    return view;
}

- (void)getBanner{
    NSString *url = [NSString stringWithFormat:@"%@%@",HOST, @"banner/item"];
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:nil ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"项目banner ---- %@",responseResult);
        if ([self.collectionView.mj_header isRefreshing]) {
            [self.collectionView.mj_header endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSDictionary *data = responseResult[@"data"];
                NSArray *banner = data[@"banner"];
                
                [self.bannerArr removeAllObjects];
                
                for (NSDictionary *dic in banner) {
                    CYBannerModel *model = [CYBannerModel modelWithDictionary:dic];
                    [self.bannerArr addObject:model];
                }
                
                [self.collectionView reloadData];
                
            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

- (void)getData{
    self.page = 1;
    NSString *url = [NSString stringWithFormat:@"%@%@",HOST, @"index"];
    NSDictionary *param = @{@"type":@3};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"项目列表 ---- %@",responseResult);
        if ([self.collectionView.mj_header isRefreshing]) {
            [self.collectionView.mj_header endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSDictionary *data = responseResult[@"data"];
                NSArray *list = data[@"list"];
                [self.dataSourceArr removeAllObjects];
                NSMutableArray *muArr = [NSMutableArray arrayWithCapacity:0];
                for (NSDictionary *dic in list) {
                    CYProjectModel *model = [CYProjectModel mj_objectWithKeyValues:dic];
                    NSString *htmlUrl = [NSString stringWithFormat:@"%@&type=1", [self URLDecodedString:model.mobile_url]];
                    [muArr addObject:htmlUrl];
                    [self.dataSourceArr addObject:model];
                }
                [self loadHtmlWithCacheWithUrls:muArr];
                [CATransaction setDisableActions:YES];
                [self.collectionView reloadData];
                [CATransaction commit];
                
            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}


- (void)loadHtmlWithCacheWithUrls:(NSArray *)urls{
    
    STMURLCache *sCache = [STMURLCache create:^(STMURLCacheMk *mk) {
        mk.isDownloadMode(YES).isUsingURLProtocol(YES).cacheTime(20*60*60);
    }];
    [sCache preLoadByRequestWithUrls:urls];
}

-(NSString *)URLDecodedString:(NSString *)str
{
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    return decodedString;
}

- (void)getMoreData{
    self.page ++;
    NSString *url = [NSString stringWithFormat:@"%@%@",HOST, @"index"];
    NSDictionary *param = @{@"type":@3, @"page":[NSNumber numberWithInteger:self.page]};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"项目列表 ---- %@",responseResult);
        if ([self.collectionView.mj_footer isRefreshing]) {
            [self.collectionView.mj_footer endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
            self.page --;
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSDictionary *data = responseResult[@"data"];
                NSArray *list = data[@"list"];
                NSMutableArray *muArr = [NSMutableArray arrayWithCapacity:0];
                for (NSDictionary *dic in list) {
                    CYProjectModel *model = [CYProjectModel mj_objectWithKeyValues:dic];
                    NSString *htmlUrl = [NSString stringWithFormat:@"%@&type=1", [self URLDecodedString:model.mobile_url]];
                    [muArr addObject:htmlUrl];
                    [self.dataSourceArr addObject:model];
                }
                [self loadHtmlWithCacheWithUrls:muArr];

                [CATransaction setDisableActions:YES];
                [self.collectionView reloadData];
                [CATransaction commit];
                
            }else{
                self.page --;
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

- (void)getCate{
    NSString *url = [NSString stringWithFormat:@"%@%@",HOST, @"cate-gory/item"];
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:nil ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"分类列表 ---- %@",responseResult);
        if ([self.collectionView.mj_header isRefreshing]) {
            [self.collectionView.mj_header endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSArray *data = responseResult[@"data"];
                self.data = data;
                [self.cateArr removeAllObjects];
                for (NSDictionary *dic in data) {
                    CYCategrayModel *model = [CYCategrayModel modelWithDictionary:dic];
                    [self.cateArr addObject:model];
                }
                [self.collectionView reloadData];
            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}


- (UICollectionView *)collectionView{
    if (!_collectionView) {
        //居左约束
        UICollectionViewFlowLayout *leftAlignedLayout = [[UICollectionViewFlowLayout alloc] init];
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, kWindowH - Height_TabBar - Height_NavBar) collectionViewLayout:leftAlignedLayout];
        _collectionView.backgroundColor = BackGroundColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        [_collectionView registerNib:[UINib nibWithNibName:@"CYProjectBannerCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CYProjectBannerCollectionViewCell"];
        
        [_collectionView registerNib:[UINib nibWithNibName:@"CYProjectLabelCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CYProjectLabelCollectionViewCell"];
        [_collectionView registerNib:[UINib nibWithNibName:@"CYProjectCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CYProjectCollectionViewCell"];
        
        [_collectionView registerNib:[UINib nibWithNibName:@"CYImageCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CYImageCollectionViewCell"];

        [_collectionView registerNib:[UINib nibWithNibName:@"CYProjectHeaderCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CYProjectHeaderCollectionReusableView"];
        
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self getData];
            [self getBanner];
            [self getCate];
        }];
        
        _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [self getMoreData];
        }];
        
    }
    return _collectionView;
}


- (NSMutableArray *)bannerArr{
    if (!_bannerArr) {
        _bannerArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _bannerArr;
}
- (NSMutableArray *)dataSourceArr{
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArr;
}

- (NSMutableArray *)cateArr{
    if (!_cateArr) {
        _cateArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _cateArr;
}

- (HW3DBannerView *)banner{
    if (!_banner) {
        _banner = [HW3DBannerView initWithFrame:CGRectMake(0, 10, kWindowW, 120) imageSpacing:10 imageWidth:kWindowW - 60];
        _banner.initAlpha = 1; // 设置两边卡片的透明度
        _banner.imageRadius = 10; // 设置卡片圆角
        _banner.imageHeightPoor = 10; // 设置中间卡片与两边卡片的高度差
        _banner.placeHolderImage = [UIImage imageNamed:@""]; // 设置占位图片
        _banner.curPageControlColor = RGBOF(0xF03333);
        _banner.otherPageControlColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        __weak typeof(self)weakself = self;
        _banner.clickImageBlock = ^(NSInteger currentIndex) { // 点击中间图片的回调
            CYProjectDetailViewController *detail = [[CYProjectDetailViewController alloc] init];
            CYBannerModel *banner = weakself.bannerArr[currentIndex];
            NSMutableDictionary *mudic = [banner mj_keyValues];
            [mudic setObject:mudic[@"ID"] forKey:@"id"];
            [mudic removeObjectForKey:@"ID"];
            detail.model = [CYProjectModel mj_objectWithKeyValues:mudic];
            [[AppDelegate sharedAppDelegate] pushViewController:detail];
        };
        //隐藏pageControl
    }
    return _banner;
}


@end
